package com.red.wine.ui;

import java.io.IOException;



import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.red.weixin.Constants;
import com.red.wine.R;
import com.red.wine.model.BindData;
import com.red.wine.model.BindReq;
import com.red.wine.model.Headers;
import com.red.wine.model.RegetPassData;
import com.red.wine.model.RegetPassReq;
import com.red.wine.model.RegisterReturn;
import com.red.wine.util.DialogUtil;
import com.red.wine.util.IntentUtil;
import com.red.wine.util.PrefsUtils;
import com.red.wine.util.StringUtil;
import com.red.wine.webservice.ServiceAsynTask;
import com.red.wine.webservice.ServiceHelper;
import com.red.wine.webservice.ServiceHost;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.ConstantsAPI;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.ShowMessageFromWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXAppExtendObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;
import com.tencent.weibo.api.RequestAPI;
import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv1.OAuthV1;
import com.tencent.weibo.oauthv1.OAuthV1Client;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MyCenterActivity extends BaseActivity implements IWXAPIEventHandler{
	private ImageView back;
	private Button setBtn;
	private TextView shoucang;
	private TextView fankui;
	private TextView aboutour;
	private TextView share_xinlang;
	private TextView share_tengxun;
	private TextView share_weixin;
	private TextView dyname;
	private TextView dysex;
	private TextView dycity;
	private Context context;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_center);
		context = this;
		
		// 通过WXAPIFactory工厂，获取IWXAPI的实例
//    	api = WXAPIFactory.createWXAPI(this, ConstantS.APP_ID, false);
		
		back = (ImageView) findViewById(R.id.top_back_btn_3);
		setBtn = (Button) findViewById(R.id.center_edit_btn);
		shoucang = (TextView) findViewById(R.id.wodeshoucang);
		fankui = (TextView) findViewById(R.id.cen_yijianfankui);
		aboutour = (TextView) findViewById(R.id.cen_about_our);
		share_xinlang = (TextView) findViewById(R.id.share_xinlang);
		share_tengxun = (TextView) findViewById(R.id.share_tengxun);
		share_weixin = (TextView) findViewById(R.id.share_weixin);
		dyname = (TextView) findViewById(R.id.dy_center_name);
		dysex = (TextView) findViewById(R.id.center_sexs);
		dycity = (TextView) findViewById(R.id.center_city);
		if (!StringUtil.isEmptyOrNull(PrefsUtils.getDyName())) {
			dyname.setText(PrefsUtils.getDyName());
		} else {
			dyname.setText("昵称未设置");
		}

		if (!StringUtil.isEmptyOrNull(PrefsUtils.getSex())) {
			dysex.setText("性别：" + PrefsUtils.getSex());
		} else {
			dysex.setText("性别未设置");
		}

		if (!StringUtil.isEmptyOrNull(PrefsUtils.getCity())) {
			dycity.setText("所在城市：" + PrefsUtils.getCity());
		} else {
			dycity.setText("所在城市未设置");
		}
		back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});
		fankui.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				IntentUtil.redirectToNext(context, FeedBackActivity.class);
				finish();
			}
		});
		setBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				IntentUtil.redirectToNext(context, PerInfoActivity.class);
				finish();
			}
		});
		shoucang.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				IntentUtil.redirectToNext(context, FavoritesActivity.class);
				finish();
			}
		});
		aboutour.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				IntentUtil.redirectToNext(context, AboutOurActivity.class);
				finish();
			}
		});
		share_xinlang.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
//				String url = "http://wine.5do.com/sina/index.php";
//				showLoading();
//				Intent intent = new Intent();        
//		        intent.setAction("android.intent.action.VIEW");    
//		        Uri content_url = Uri.parse(url);   
//		        intent.setData(content_url);  
//		        startActivity(intent);
//				hideLoading();
				new AlertDialog.Builder(context).setTitle("未绑定新浪微博，是否现在绑定").setPositiveButton("确定", new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						try{
						}catch(Exception e){}
						dialog.dismiss();
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create().show();
			}
		});
	
		share_tengxun.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				
			}
		});
		builder = new AlertDialog.Builder(context);
		view = LayoutInflater.from(context).inflate(R.layout.share_content,null);
		content = (EditText) view.findViewById(R.id.share_put_edit);
		isTimelineCb = (CheckBox)view.findViewById(R.id.is_timeline_cb);
		isTimelineCb.setChecked(false);
		builder.setView(view);
		// 将该app注册到微信
		  // 通过WXAPIFactory工厂，获取IWXAPI的实例
		api = WXAPIFactory.createWXAPI(MyCenterActivity.this, Constants.APP_ID, false);
  	// 将该app注册到微信
	    api.registerApp(Constants.APP_ID); 
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				String text = content.getText().toString();
				if (text == null || text.length() == 0) {
					return;
				}
				
				// 初始化一个WXTextObject对象
				WXTextObject textObj = new WXTextObject();
				textObj.text = text;

				// 用WXTextObject对象初始化一个WXMediaMessage对象
				WXMediaMessage msg = new WXMediaMessage();
				msg.mediaObject = textObj;
				// 发送文本类型的消息时，title字段不起作用
				// msg.title = "Will be ignored";
				msg.description = text;

				// 构造一个Req
				SendMessageToWX.Req req = new SendMessageToWX.Req();
				req.transaction = buildTransaction("text"); // transaction字段用于唯一标识一个请求
				req.message = msg;
				req.scene = isTimelineCb.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
				
				// 调用api接口发送数据到微信
				api.sendReq(req);
				shareDialog.dismiss();
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				shareDialog.dismiss();
			}
		});
		shareDialog = builder.create();
		share_weixin.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				 
			    showLoading();
			    new Thread(){public void run() {
			    	try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			    };}.start();
			    hideLoading();
			    int wxSdkVersion = api.getWXAppSupportAPI();
				if (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION) {
					shareDialog.show();
				} else {
					Toast.makeText(MyCenterActivity.this, "不能分享信息到朋友圈，请检测是否安装微信", Toast.LENGTH_LONG).show();
				}
				api.handleIntent(getIntent(), MyCenterActivity.this);
			}
		});
		 
	}
	
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
	}
	private CheckBox isTimelineCb;
	private static final int THUMB_SIZE = 150;
	View view;
	EditText content;
	private Dialog shareDialog;
	private Builder builder;
	private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
	// IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;
	
	
	// 微信发送请求到第三方应用时，会回调到该方法
	public void onReq(BaseReq req) {
		switch (req.getType()) {
		case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
			goToGetMsg();		
			break;
		case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
			goToShowMsg((ShowMessageFromWX.Req) req);
			break;
		default:
			break;
		}
	}

	// 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
	public void onResp(BaseResp resp) {
		int result = 0;
		
		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK:
//			result = R.string.errcode_success;
			break;
		case BaseResp.ErrCode.ERR_USER_CANCEL:
//			result = R.string.errcode_cancel;
			break;
		case BaseResp.ErrCode.ERR_AUTH_DENIED:
//			result = R.string.errcode_deny;
			break;
		default:
//			result = R.string.errcode_unknown;
			break;
		}
		
		Toast.makeText(this, result, Toast.LENGTH_LONG).show();
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		setIntent(intent);
        api.handleIntent(intent, this);
	}
	private void goToGetMsg() {
//		Intent intent = new Intent(this, GetFromWXActivity.class);
//		intent.putExtras(getIntent());
//		startActivity(intent);
//		finish();
	}
	
	private void goToShowMsg(ShowMessageFromWX.Req showReq) {
		WXMediaMessage wxMsg = showReq.message;		
		WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;
		
		StringBuffer msg = new StringBuffer(); // 组织一个待显示的消息内容
		msg.append("description: ");
		msg.append(wxMsg.description);
		msg.append("\n");
		msg.append("extInfo: ");
		msg.append(obj.extInfo);
		msg.append("\n");
		msg.append("filePath: ");
		msg.append(obj.filePath);
		
//		Intent intent = new Intent(this, ShowFromWXActivity.class);
//		intent.putExtra(Constants.ShowMsgActivity.STitle, wxMsg.title);
//		intent.putExtra(Constants.ShowMsgActivity.SMessage, msg.toString());
//		intent.putExtra(Constants.ShowMsgActivity.BAThumbData, wxMsg.thumbData);
//		startActivity(intent);
//		finish();
	}
}
